import { Button, Flex, Input, Space, Tree, message, Modal } from "antd";
import { useState, useEffect, useMemo, forwardRef, useImperativeHandle } from "react";
import { useQuery } from "@tanstack/react-query";
import { expandTree } from "@/utils";
import { ModalForm, ProFormSelect, ProFormText } from "@ant-design/pro-components";
import { ExclamationCircleFilled } from '@ant-design/icons';
import {
  dataCatalogTree,
  dataCatalogUpdate,
  dataCatalogAdd,
  dataCatalogDetail,
  dataCatalogDelete,
  dataResourceAdd
} from "@/api/sharing/dataCatalog";
import Scrollbar from "@/components/scrollbar";


const findMenuItem = (arr, code, key = 'id') => {
  let result;
  arr.find((d) => {
    if (d[key] === code) {
      result = d
      return true
    } else if (d.children) {
      result = findMenuItem(d.children, code, key)
      return Boolean(result)
    }
  })
  return result
}

const SelectCatalogTree = forwardRef((props, ref) => {

  const { wantRoot, id, rootName, onTreeChange } = props
  const [nodeData, setNodeData] = useState()
  const [queryParam, setQueryParam] = useState({
    resourceName: ''
  });
  const [expandedKeys, setExpandedKeys] = useState([]);

  useImperativeHandle(ref, () => ({
    refetch: refetch,
  }));

  const { data: treeData, isFetching, refetch } = useQuery({
    queryKey: ['SelectCatalogTree-dataCatalogTree'],
    initialData: props.treeData,
    queryFn: () => {
      return dataCatalogTree().then((res) => {
        return res.result || []
      })
    },
    staleTime: 0,
  })

  const treeOptions = useMemo(() => {
    if (wantRoot && !queryParam.resourceName) {
      return [
        {
          id: '-1',
          catalogName: rootName || '根节点',
          childTreeList: treeData || [],
        }
      ]
    }
    return treeData
  }, [treeData, wantRoot])

  useEffect(() => {
    if (treeOptions) {
      setExpandedKeys(expandTree(treeOptions, 3))
      onTreeChange && onTreeChange([...treeOptions])
    }
  }, [treeOptions])

  const parentData = useMemo(() => {
    if (nodeData && nodeData.parentId !== '-1') {
      return findMenuItem(treeOptions, nodeData.parentId)
    }
  }, [treeOptions, nodeData])

  const onSearch = (value) => {
    setQueryParam({ resourceName: value })
  }

  const handleSave = (values) => {
    if (values.parentId === '-1') delete values.parentId;
    if (values.id) {
      return dataCatalogUpdate(values).then((res) => {
        if (res.code !== 200) return false
        refetch()
        message.success('修改成功')
        return true
      })
    } else {
      return dataCatalogAdd(values).then((res) => {
        if (res.code !== 200) return false
        refetch()
        message.success('新增成功')
        return true
      })
    }
  }

  const onSelect = (val, info) => {
    if (info.node.id === nodeData?.id) {
      setNodeData(undefined)
    } else {
      setNodeData(info.node)
    }
    props.onSelect(val, info)
  }

  const deleteConfirm = () => {
    Modal.confirm({
      title: '确认删除所选中数据?',
      icon: <ExclamationCircleFilled />,
      autoFocusButton: null,
      onOk() {
        return dataCatalogDelete(nodeData.id)
          .then((res) => {
            if (res.code === 200) {
              onSelect([], { node: nodeData })
              refetch()
              message.success('删除成功')
            }
          })
      },
      onCancel() { },
    });
  };

  return (
    <div style={Object.assign({ height: '100%' }, props.style || {})}>
      <Flex justify="center" style={{ paddingBottom: '16px' }}>
        <Space>
          <ModalForm
            trigger={<Button type="primary" size="small">新增</Button>}
            title="新增目录"
            modalProps={{ destroyOnClose: true }}
            initialValues={{
              parentId: nodeData?.id || '-1'
            }}
            onFinish={handleSave}
            width={'350px'}
          >
            <ProFormSelect disabled name="parentId" options={[
              { label: '根目录', value: '-1' },
              { label: nodeData?.catalogName, value: nodeData?.id },
            ]} />
            <ProFormText
              name="catalogName"
              label="目录名称"
              placeholder="目录名称"
              rules={[{ required: true, message: '请输入目录名称' }]}
            />
          </ModalForm>
          <ModalForm
            trigger={<Button disabled={!nodeData} type={'primary'} size="small">修改</Button>}
            title="修改目录"
            modalProps={{ destroyOnClose: true }}
            onFinish={handleSave}
            width={'350px'}
            initialValues={{
              ...nodeData
            }}
          >
            <ProFormText
              name="id"
              hidden
            />
            <ProFormSelect disabled name="parentId" options={[
              { label: '根目录', value: '-1' },
              { label: parentData?.catalogName, value: parentData?.id },
            ]} />
            <ProFormText
              name="catalogName"
              label="目录名称"
              placeholder="目录名称"
              rules={[{ required: true, message: '请输入目录名称' }]}
            />
          </ModalForm>

          <Button disabled={!nodeData} danger size="small" onClick={deleteConfirm}>删除</Button>
        </Space>
      </Flex>
      {/* {props.showSearch && <Input.Search style={{ paddingBottom: '16px' }} placeholder="输入名称回车查询" onSearch={onSearch} />} */}
      <Scrollbar style={{ height: 'calc(100% - 40px)' }} >
        <Tree
          style={{ padding: '0 12px' }}
          selectedKeys={props.selectedKeys}
          expandedKeys={expandedKeys}
          onSelect={onSelect}
          autoExpandParent={true}
          treeData={treeOptions}
          fieldNames={{
            title: 'catalogName',
            key: 'id',
            children: 'childTreeList',
          }}
          onExpand={(expandedKeys) => {
            setExpandedKeys(expandedKeys)
          }}
        ></Tree>
      </Scrollbar>
    </div>
  );
});

export default SelectCatalogTree;